function [Y, U, V] = yuvread(name, width, height, frame_number, type)
%YUVREAD read video in YUV format
%
%   [Y,U,V] = yuvread(name, width, height, frames, type)
%
%   name   : name of YUV file
%   width  : width of frame
%   height : height of frame
%   frame_number : number of the frame wanted
%   type   : YUV format
%             1 : 4:2:0
%   Y      : the selected Y frame
%   U      : the selected U frame
%   V      : the selected V frame
%
%   See also YUVWRITE.

%   Author(s): A. F. Araujo, 2010/10/25, adapted from yuvread by M. Flierl, 2006/02/01


fid = fopen(name, 'r');
if(fid == -1)
 disp(['yuvread_byframe: cannot open file: ' name]);
 Y=0; U=0; V=0;
 return;
end;

skipY = (frame_number-1)*width*height;
skipU = (frame_number-1)*width/2*height/2;
skipV = (frame_number-1)*width/2*height/2;

skipTOTAL = skipY + skipU + skipV;

switch type
 case 1,
 Y = uint8(zeros(height, width));
 U = uint8(zeros(height/2, width/2));
 V = uint8(zeros(height/2, width/2));
 
status = fseek(fid, skipTOTAL + 1, 0); 
if (status == 0)
    [Yin, cnt] = fread(fid, [width, height], 'uint8');
    [Uin, cnt] = fread(fid, [width/2, height/2], 'uint8');
    [Vin, cnt] = fread(fid, [width/2, height/2], 'uint8');
else
    disp('yuvread_byframe: cannot find location');
    Y=0; U=0; V=0;
    return;
end
  
Y(:,:) = Yin'; 
U(:,:) = Uin'; 
V(:,:) = Vin';
fclose(fid);
 
 case 0,
 Y = uint8(zeros(height, width));
 
 status = fseek(fid, skipTOTAL + 1, 0); 
 if (status == 0) [Yin, cnt] = fread(fid, [width, height], 'uint8');             
 else
    disp('yuvread_byframe: cannot find location');
    Y=0; U=0; V=0;
    return;
 end

 Y(:,:) = Yin'; 
 U = 0; V = 0;
 fclose(fid);
 
 otherwise,
 disp(['yuvread_byframe: type ' num2str(type) ' not implemented!']);
 fclose(fid);
 Y=0; U=0; V=0;
 return;
end;